import baseUrl from "./url.js";
import store from "../store/index.js";
const request = (
  url,
  data,
  method = "POST",
  contentType = "application/x-www-form-urlencoded"
) => {
  return new Promise((resolve, reject) => {
    const token = uni.getStorageSync("ai-token") || "";
    const httpDefaultOpts = {
      url: baseUrl.url + url,
      data,
      method,
	  timeout:180000,
      dataType: "json",
      withCredentials: true,
      header: {
        "x-requested-with": "XMLHttpRequest",
        "content-type": contentType,
        aiettoken: token,
      },
    };
    uni.request(httpDefaultOpts)
      .then((res) => {
        if (res.statusCode === 200) {
          console.log(res);
          if (res.data.msg === "请登录" || res.data.msg === "token无效") {
            store.state.isLogin = false
			uni.removeStorageSync("ai-token")
			store.state.user = {};
          } else if (res.data.code === 200) {
            //请求成功
            resolve(res.data);
          } else {
            console.log("发生错误的URL", url, data);
            resolve(res.data);
          }
        } else {
          console.log("发生错误的URL", url, data);
          reject(res);
        }
      })
      .catch((response) => {
        reject(response);
      });
  });
};

export default request;
